import { defineStore } from 'pinia'
import { apiGetRouterList } from '../apis/global'
import { useRoute } from 'vue-router'
export const useRouterStore = defineStore(
  'route',
  () => {
    const router = useRoute()
    const routes = ref([])
    // 二级及一下菜单，通常是菜单类型为horizontal_top的菜单
    const sonMenu = ref([])
    // 判断是否是菜单且没有页面，这种情况则把菜单当成页面处理（后续要改进）
    const folderToMenu = (routerList) => {
      return routerList.map((item) => {
        if (
          item.menuType === 'folder' &&
          (!item.children || item.children.length === 0)
        ) {
          item.menuType = 'menu'
        }
        if (item.id === 'home') {
          // 强制首页缓存
          item.meta.noCache = true
        }
        return item
      })
    }
    // 删除多余斜线，目前接口问题，后续不需要
    // const delBias = (routerList) => {
    //   return routerList.map((item) => {
    //     if (Array.isArray(item.children)) {
    //       item.children = delBias(item.children)
    //     }
    //     if (item.path && item.path.slice(0, 2) === '//') {
    //       item.path = item.path.slice(1)
    //     }
    //     return item
    //   })
    // }
    const getRouter = async () => {
      return new Promise(async (resolve, reject) => {
        const resData = await apiGetRouterList()
        routes.value = folderToMenu(resData)
        if (routes.value.length > 0) {
          sonMenu.value = routes.value[0].children || []
        }
        resolve(routes.value)
      })
    }
    // 遍历路由找到顶级路由
    const getTopMenu = (routerList, path) => {
      for (let i = 0; i < routerList.length; i++) {
        const route = routerList[i]
        if (route.path === path) {
          return route
        }
        if (route.children) {
          const result = getTopMenu(route.children, path)
          if (result) {
            return route
          }
        }
      }
      return null
    }
    return {
      routes,
      getRouter,
    }
  },
  {
    persist: {
      enabled: true, //Store中数据持久化生效
    },
  }
)
